package br.dcc.ufmg.xml;

import java.io.File;

import br.dcc.ufmg.persistence.MetricDAO;
import br.dcc.ufmg.xml.Metrics.Metric.Values.Value;

public class XmlFileToDatabase {

	private MetricDAO metricDAO;

	private ParserXml parserXml;

	public XmlFileToDatabase(File xmlFile) {
		parserXml = new ParserXml(xmlFile);
		metricDAO = new MetricDAO();
	}

	private void importMetric (String id, String description) throws Exception {
		if (!metricDAO.isInserted(id)) {
			metricDAO.insertMetric(id, description);
		}
	}

	public boolean importFileToDatabase(String system) throws Exception {
		boolean success = false;
		if (parserXml.isXmlValid()) {
			Metrics metrics = parserXml.getMetricsFromXml();
			metricDAO.insertSource(metrics.getScope(), system);
			for (Metrics.Metric metric : metrics.metric) {
				importMetric(metric.getId(), metric.getDescription());
				importMeasurement(metrics, metric);
				importMeasure(metrics, metric);
			}
		}
		return success;
	}

	private void importMeasure(Metrics metrics, Metrics.Metric metric)
			throws Exception {
		if (metric.getValue() != null) {
			metricDAO.insertMeasure(metric.getId(), metrics.getScope(), Float.valueOf(metric
					.getValue().getValue()));
		} else if (metric.getValues() != null) {
			for (Value value : metric.getValues().getValue()) {
				metricDAO.insertMeasure(metric.getId(), metrics.getScope(),
						value);
			}
		}
	}

	private void importMeasurement(Metrics metrics, Metrics.Metric metric)
			throws Exception {
		if (metric.getValue() != null) {
			metricDAO.insertMeasurement(metric.getId(), metrics.getScope(),
					"system");
		} else if (metric.getValues() != null) {
			metricDAO.insertMeasurement(metric.getId(), metrics.getScope(),
					metric.getValues().getPer());
		}
	}

}
